<?php
/**
 * <pre>
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Hyundai
 * COPYRIGHT	: 2008
 * ------------------------------------------------------
 * 
 * [GENERAL INFO OF THIS FILE] 
 * 
 * </pre>
 * 
 * Created on	:  Oct 4, 2008
 * 
 * @author		sanglt <sanglt@rubik.com.vn>
 * @access		[public/private]
 * @package		[package name]
 *
 */

class RURLHelper {
	
	/**
	 * Get Request by use .htaccess
	 * .htaccess Content:
	 * 
	 * <IfModule mod_rewrite.c>
	 * RewriteEngine on
	 * RewriteCond %{REQUEST_FILENAME} !-f
	 * RewriteCond %{REQUEST_FILENAME} !-d
	 * RewriteRule ^(.*)$ index.php?_rurq=$1 [L,QSA]
	 * </IfModule>
	 * 
	 * @param string $mapString: Use Regular Expressions, it will map to array.
	 * Use [] to add optional for param and number length input or array map.
	 * Example: [lang:3]/app/act/task
	 * [lang:vi|en]/app/[act:3]/task
	 * If input was long than string, it will map at: a/b
	 * Ex: [lang:vi|en]/app/[act:3]/task and input was long than task: vi/app/act/task/ext1/ext2/ext3/ext4.. => will map ext1=ext2, ext3=ext4
	 * ...
	 */
	static function getRequest($mapString, $subfix = '.html') {
		$request = $_REQUEST['_rurq'];
		$request = str_replace($subfix, '', $request);
		$requestArray = explode('/', $request);
		$mapString = explode('/', $mapString);
		$returnArray = array();
		$i = 0;
		foreach( $mapString as $map) {
			$matches = null;
			if (preg_match('#\[(.*?)\]#', $map, $matches)) {
				if ($strHash = RURLHelper::mapString($matches[1], $requestArray[$i])) {
					$returnArray[$strHash[0]] = $strHash[1];
					$i++;
				}
			} else {
				if (strpos($requestArray[$i], ':') !== false) {
					continue;
				}
				$returnArray[$map] = $requestArray[$i];
				$i++;
			}
		}
		$numParamRequest = count($requestArray);
		$numParamReturn = count($returnArray);
		if ($numParamRequest > $numParamReturn) {
			for ($i = $numParamReturn; $i < $numParamRequest; $i++){
				$mapCheck = explode(':', $requestArray[$i]);
				if(isset($mapCheck[1])) {
					$returnArray[$mapCheck[0]] = $mapCheck[1];
				} else {
					$returnArray[$i] = $requestArray[$i];
				}
			}
		}
		return $returnArray;
	}
	
	/**
	 * Map string in pattern
	 *
	 * @param $strCheck
	 * @param str $strNeed
	 */
	static function mapString($strCheck, $strNeed, $charCode = ':') {
		$strCheckArray = explode($charCode, $strCheck);
		// Check if number
		if(is_numeric($strCheckArray[1])) {
			// Check if strNeed was too long
			if (strlen($strNeed) == $strCheckArray[1]) {
				//return array($strCheckArray[0], substr($strNeed, 0, $strCheckArray[1]));
				return array($strCheckArray[0], $strNeed);
			}
		} else {
			$strHash = explode('|', $strCheckArray[1]);
			if (in_array($strNeed, $strHash)) {
				return array($strCheckArray[0], $strNeed);
			}
		}
		return false;
	}
}
?>
